package self.nutz.demo.module;

import java.util.List;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpSession;

import org.nutz.dao.Cnd;
import org.nutz.dao.Dao;
import org.nutz.ioc.loader.annotation.Inject;
import org.nutz.ioc.loader.annotation.IocBean;
import org.nutz.mvc.annotation.At;
import org.nutz.mvc.annotation.Fail;
import org.nutz.mvc.annotation.Ok;
import org.nutz.mvc.annotation.Param;

import self.nutz.demo.dao.User;

/** 
* @author Cherokees Yin
* @version 2016年10月30日 下午4:24:06 
* @description 
*/

@IocBean
@At("/user")
@Ok("json")
@Fail("http:500")
public class UserModule {
	
	@Inject
	protected Dao dao;
	
	@At("/count")
	public int count(){
		return dao.count(User.class);
	}
	
	@At("/query")
	public List<User> query(){
		List<User> userList = dao.query(User.class, Cnd.where("name", "LIKE", "ad%").asc("id"));
		return userList;
	}
	
	/**
	 * 
	 * @param username http参数,@Param为nutz内置注解,用于传递http请求中的参数
	 * @param pwd http参数
	 * @param session 服务器创建的session，用于存放用户数据
	 * @return
	 */
	@At
	public Object login(@Param("username")String username,@Param("password")String pwd,HttpSession session){
		
		User user = dao.fetch(User.class, Cnd.where("name", "=", username).and("password", "=", pwd));
		if(user == null){
			return false;
		}else{
			session.setAttribute("管理员", user);
			return true;
		}
	}
	/**
	 * 
	 * @param request httpservletrequest返回服务器的session对象
	 * @return
	 */
	@At
	public Object sessionUser(HttpServletRequest request){
		HttpSession session = request.getSession();
		if(session.isNew()){
			return "session是新建的";
		}else{
		User admin = (User)session.getAttribute("管理员");
		return admin;
		}
	}

}
